package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.SearchEnum;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.company.bean.FlowEnum;
import com.fz.us.admin.company.entity.Company;
import com.fz.us.admin.company.entity.TaskEntity;
import com.fz.us.admin.company.entity.User;
import com.fz.us.oa.core.entity.com.BusinessTravel;
import com.fz.us.oa.core.entity.common.FileManage;
import com.fz.us.oa.core.service.com.BusinessTravelService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by dzw on 2017/12/8.
 */
@Controller
@RequestMapping(value = "/com/businessTravel")
public class BusinessTravelController extends BaseController {
    private static final long serialVersionUID = -4268545458904854272L;

    @Autowired
    private BusinessTravelService businessTravelService;

    /**
     * 列表
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,Model model,
                                    String viewtype,
                                    JqGridPager pager,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        Company company = user.getCompany();
        // 排序
        Order order = Order.order("createTime", SearchEnum.OrderType.desc);
        SearchResultPaging searchResult = null;
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("company", company);
        params.put("state", BaseEnumManager.StateEnum.Enable);
        if(StringUtils.isNotEmpty(viewtype)) {
            if ("1".equals(viewtype)) {
                //申请中
                searchResult = businessTravelService.paging(order,
                        "com.fz.us.oa.core.entity.com.BusinessTravel", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed},params);
            }else if("2".equals(viewtype)){
                //已通过
                params.put("isFinished", 0);
                searchResult =  businessTravelService.paging(order,
                        "com.fz.us.oa.core.entity.com.BusinessTravel", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished},params);
            }else if("3".equals(viewtype)){
                //已完成
                params.put("isFinished", 1);
                searchResult =  businessTravelService.paging(order,
                        "com.fz.us.oa.core.entity.com.BusinessTravel", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished}, params);
            }
        }else{
            //所有单子
            searchResult = businessTravelService.paging(order,
                    "com.fz.us.oa.core.entity.com.BusinessTravel",
                    new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny}, params);
        }
        List<BusinessTravel> businessTravelList = searchResult.getList();
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(BusinessTravel businessTravel: businessTravelList){
            TaskEntity taskEntity = taskEntityService.getInfoByKeyId(businessTravel.getId());
            Set<User> users = taskEntity.getEditors();
            String editor = "";
            for(User editorName:users){
                editor += editorName.getName()+",";
            }
            if(StringUtils.isNotEmpty(editor)){
                editor = editor.substring(0, editor.length()-1);
            }
            rMap = new HashMap<String, Object>();
            rMap.put("id",businessTravel.getId());
            rMap.put("travelUser", businessTravel.getTravelUser()==null?"":businessTravel.getTravelUser().getName());
            rMap.put("travelStartDate", DataUtil.DateToString(businessTravel.getTravelStartDate(),"yyyy-MM-dd"));
            rMap.put("reason", businessTravel.getReason());
            rMap.put("address", businessTravel.getAddress());
            rMap.put("money", businessTravel.getMoney());
            rMap.put("editor", editor);
            rMap.put("isComplete", businessTravel.getIsComplete());
            dataRows.add(rMap);
        }
        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());
        return data;
    }

    /**
     * 新建，编辑页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {

        if (StringUtils.isNotEmpty(keyId)){
            BusinessTravel businessTravel=businessTravelService.get(keyId);
            model.addAttribute("keyId", keyId);
            model.addAttribute("businessTravel", businessTravel);
        }
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        model.addAttribute("user", user);
        return "/com/businessTravel_input";
    }

    /**
     * 只读页面
     */
    @RequestMapping(value = "read", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {

        if(StringUtils.isNotEmpty(keyId)) {
            BusinessTravel businessTravel=businessTravelService.get(keyId);
            String userEdit = userEdit(keyId);
            model.addAttribute("businessTravel", businessTravel);
            model.addAttribute("userEdit", userEdit);

            String failFileId="";
            String summaryFileId="";
            if(businessTravel.getFailFile()!=null && businessTravel.getFailFile().size()>0){
                for(FileManage file:businessTravel.getFailFile()){
                    failFileId+=file.getId()+",";
                }
            }
            if(businessTravel.getSummaryFile()!=null && businessTravel.getSummaryFile().size()>0){
                for(FileManage file:businessTravel.getSummaryFile()){
                    summaryFileId+=file.getId()+",";
                }
            }

            model.addAttribute("failFileId", failFileId);
            model.addAttribute("summaryFileId", summaryFileId);

        }
        model.addAttribute("keyId", keyId);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/businessTravel_read";
    }

    /**
     * 复制数据
     */
    public BusinessTravel setData(User user, String keyId, String travelUserId, String travelStartDate, String travelEndDate, String reason,
                                  String address, BigDecimal money){
        BusinessTravel businessTravel=null;
        if(StringUtils.isEmpty(keyId)){
            businessTravel=new BusinessTravel();
            businessTravel.setCreater(user);
            businessTravel.setCompany(user.getCompany());
        }else{
            businessTravel=businessTravelService.get(keyId);
        }
        businessTravel.setTravelUser(userService.get(travelUserId));
        businessTravel.setTravelStartDate(DataUtil.StringToDate(travelStartDate));
        businessTravel.setTravelEndDate(DataUtil.StringToDate(travelEndDate));
        businessTravel.setReason(reason);
        businessTravel.setAddress(address);
        businessTravel.setMoney(money);

        return businessTravel;
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user, String keyId, String travelUserId, String travelStartDate, String travelEndDate, String reason,
                       String address, BigDecimal money) {
        Map<String,Object> rMap=new HashMap<String,Object>();
        BusinessTravel businessTravel=setData(user,keyId,travelUserId,travelStartDate,travelEndDate,reason,address,money);
        if(StringUtils.isNotEmpty(keyId)){
            businessTravelService.update(businessTravel);
            rMap.put("message", "更新成功");
        } else {
            businessTravelService.save(businessTravel, "com.fz.us.oa.core.entity.com.BusinessTravel");
            rMap.put("message", "保存成功");
        }
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    // 提交
    @RequestMapping(value = "commit", method = RequestMethod.POST)
    public Object commit(@CurrentUser User user, String keyId, String travelUserId, String travelStartDate, String travelEndDate, String reason,
                         String address, BigDecimal money, String comment, String next, String editorsId, String remindUserId){
        User editor = null;
        if(StringUtils.isNotEmpty(editorsId)){
            editor = userService.get(editorsId);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        BusinessTravel businessTravel=setData(user,keyId,travelUserId,travelStartDate,travelEndDate,reason,address,money);
        if (StringUtils.isNotEmpty(keyId)) {
            businessTravelService.approve(businessTravel, user, comment, next, editor);
        } else {
            keyId=businessTravelService.commit(businessTravel, "com.fz.us.oa.core.entity.com.BusinessTravel", user, next, editor);
        }
        toRemind("businessTravel", keyId, remindUserId, user.getName()+"提交的出差申请，请查看");
        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //审批
    @RequestMapping(value = "approve", method = RequestMethod.POST)
    public Object approve(@CurrentUser User user, String keyId,  String comment, String next, String editorsId, String remindUserId){
        User editor = null;
        if(StringUtils.isNotEmpty(editorsId)){
            editor = userService.get(editorsId);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        BusinessTravel businessTravel=businessTravelService.get(keyId);
        businessTravelService.approve(businessTravel, user, comment, next, editor);
        toRemind("businessTravel", keyId, remindUserId, user.getName() + "提交的出差申请，请查看");
        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //退回
    @RequestMapping(value = "back", method = RequestMethod.POST)
    public Object back(@CurrentUser User user, String keyId,String backStepNo, String comment, String remindUserId) {
        if (StringUtils.isNotEmpty(keyId)) {
            BusinessTravel businessTravel=businessTravelService.get(keyId);
            if(StringUtils.isNotEmpty(backStepNo)){
                String[] arr = backStepNo.split("\\|");
                int stepNo = Integer.parseInt(arr[0]);
                User editor = userService.get(arr[1]);
                businessTravelService.back(businessTravel, comment, stepNo, editor);
                toRemind("businessTravel", keyId, remindUserId, user.getName() + "退回的出差申请，请查看");
            }
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","退回成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //否决
    @RequestMapping(value = "deny", method = RequestMethod.POST)
    public Object deny(@CurrentUser User user, String keyId, String comment, String remindUserId) {
        if (StringUtils.isNotEmpty(keyId)) {
            BusinessTravel businessTravel=businessTravelService.get(keyId);
            businessTravelService.deny(businessTravel, comment);
            toRemind("businessTravel", keyId, remindUserId, user.getName()+"否决的出差申请，请查看");
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","否决成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 验证身份
     */
    @RequestMapping(value = "checkUser", method = RequestMethod.GET)
    public Object checkUser(@CurrentUser User user, String keyId){
        if(StringUtils.isEmpty(keyId)) return ajaxJson(resultService.fail("找不到文档ID"));
        BusinessTravel businessTravel=businessTravelService.get(keyId);
        if(businessTravel==null) return ajaxJson(resultService.fail("找不到文档"));

        if(user.equals(businessTravel.getTravelUser())){
           return ajaxJson(resultService.success("验证通过"));
        }else{
            return ajaxJson(resultService.fail("需要由出差人员操作"));
        }
    }

    /**
     * 出差完成页面
     */
    @RequestMapping(value = "businessTravelFinishPage", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String businessTravelFinishPage(@CurrentUser User user, String keyId, Model model){
        model.addAttribute("businessTravelId",keyId);
        return "/com/businessTravel_finish_input";
    }

    /**
     *完成操作
     */
    @RequestMapping(value = "saveFinish", method = RequestMethod.POST)
    public Object saveFinish(@CurrentUser User user, String businessTravelId, String isComplete, String failReason, String travelSummary,
                             String failFileIds, String summaryFileIds){
        if(StringUtils.isEmpty(businessTravelId)) return ajaxJson(resultService.fail("找不到ID"));
        BusinessTravel businessTravel=businessTravelService.get(businessTravelId);
        if(businessTravel!=null){
            businessTravel.setIsFinished(1);
            businessTravel.setIsComplete(isComplete);
            if("是".equals(isComplete)){
                businessTravel.setTravelSummary(travelSummary);
                if(StringUtils.isNotEmpty(summaryFileIds)){
                    List<FileManage> fileManageList=new ArrayList<FileManage>();
                    for(String s:summaryFileIds.split(",")){
                        fileManageList.add(fileManagerService.get(s.trim()));
                    }
                    businessTravel.setSummaryFile(fileManageList);
                }
            }else{
                businessTravel.setFailReason(failReason);
                if(StringUtils.isNotEmpty(failFileIds)){
                    List<FileManage> fileManageList=new ArrayList<FileManage>();
                    for(String s:failFileIds.split(",")){
                        fileManageList.add(fileManagerService.get(s.trim()));
                    }
                    businessTravel.setFailFile(fileManageList);
                }
            }
            businessTravelService.update(businessTravel);
            return ajaxJson(resultService.success("已完成"));
        }else{
            return ajaxJson(resultService.fail("找不到文档"));
        }
    }

}
